package com.gjzt.business.customer.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eastdigit.servlet.ReqBean;
import com.eastdigit.system.model.BusinessException;
import com.eastdigit.system.model.SqlBuilder;
import com.eastdigit.system.model.User;
import com.eastdigit.system.service.BaseService;
import com.eastdigit.system.service.UserService;
import com.eastdigit.util.DateUtil;
import com.eastdigit.util.StringUtil;
import com.gjzt.business.customer.inter.CustomerMapper;
import com.gjzt.business.customer.model.Customer;
import com.gjzt.business.utils.Constant;

@Service
public class CustomerService extends BaseService {

    @Autowired
    private CustomerMapper customerMapper;
    
    @Autowired
    UserService userService;

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    public JSONObject findAdCustomer(ReqBean reqBean) {

        String quickSearch = reqBean.getInfo("quickSearch");
        SqlBuilder sqlBuilder = null;
        // 是快速查询
        if (StringUtils.isNotBlank(quickSearch) && quickSearch.equals(Constant.QUICK_SEARCH_TRUE)) {
            sqlBuilder = new SqlBuilder(
                    "select a.*,CONCAT(a.PROVINCE,'-',a.CITY,'-',a.COUNTY) provinceContent from AD_CUSTOMER a where 1=1")
                    .addWhereLike2("a.CUSTOMER_NAME", reqBean.getInfo("quickSearchName"));
        } else {
            sqlBuilder = new SqlBuilder(
                    "select a.*,CONCAT(a.PROVINCE,'-',a.CITY,'-',a.COUNTY) provinceContent from AD_CUSTOMER a where 1=1 ")
                    .addWhere("a.CUSTOMER_TYPE", reqBean.getInfo("customerType"))
                    .addWhere("a.STATUS", reqBean.getInfo("status"))
                    .addWhereLike2("a.CUSTOMER_NAME", reqBean.getInfo("customerName"))
                    .addWhereLike2("a.CONTACTS_PHONE", reqBean.getInfo("contactsPhone"));
        }
        return this.queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 新增
     * 
     * @param reqBean
     */
    public void addAdCustomer(ReqBean reqBean) {
        Customer customer = getAdCustomer(reqBean);
        customer.setCustomerId(intIncrementId("AD_CUSTOMER", "CUSTOMER_ID"));
        customer.setStatus(Customer.STATUS_TRUE);
        customerMapper.insert(customer);
    }
    
    public Customer getCusomerInfo(String customerId){
    	return customerMapper.selectByPrimaryKey(customerId);
    }

    /**
     * 修改
     * 
     * @param reqBean
     */
    public void updateAdCustomer(ReqBean reqBean) {
        String customerId = reqBean.getInfo("customerId");
        if (StringUtil.isEmpty(customerId)) {
            throw new BusinessException("获取主键失败");
        }
        Customer customer = getAdCustomer(reqBean);
        customerMapper.updateByPrimaryKeySelective(customer);
    }

    /**
     * 失效
     * 
     * @param reqBean
     */
    public void disableCustomer(ReqBean reqBean) {
        String customerId = reqBean.getInfo("customerId");
        if (StringUtil.isEmpty(customerId)) {
            throw new BusinessException("获取主键失败");
        }
        customerMapper.updateCustomerStatus(customerId, Customer.STATUS_FALSE);
        User user = userService.queryBySource(User.TYPE_CUSTOMER, customerId);
        if(user != null){
        	user.setState("0");
        	userService.update(user);
        }
    }
    
    public void settingCustomerUser(String customerId,ReqBean reqBean){
    	Customer customer = customerMapper.selectByPrimaryKey(customerId);
    	String userCode = reqBean.getInfo("code");
    	String userState = reqBean.getInfo("state");
    	String remark = reqBean.getInfo("remark");
        
        User user = userService.queryBySource(User.TYPE_CUSTOMER, customerId);
        user = user == null ? new User() : user;
        user.setType(User.TYPE_CUSTOMER);
        user.setSourceId(customerId);
    	user.setName(customer.getCustomerName());
    	user.setCode(userCode);
    	user.setState(userState);
    	user.setRemark(remark);
    	
    	if(StringUtil.isEmpty(user.getId())){
    		userService.add(user);
    	}else{
    		userService.update(user);
    	}
    }

    /**
     * 从表单获取对象
     * 
     * @param reqBean
     * @return
     */
    private Customer getAdCustomer(ReqBean reqBean) {
        Customer customer = new Customer();

        customer.setCustomerId(reqBean.getInfo("customerId"));
        customer.setCustomerName(reqBean.getInfo("customerName"));
        customer.setCustomerType(reqBean.getInfo("customerType"));
        customer.setBusinessLicense(reqBean.getInfo("businessLicense"));
        customer.setBusinessLicenseImg(reqBean.getInfo("businessLicenseImg"));
        customer.setOrgCertificate(reqBean.getInfo("orgCertificate"));
        customer.setOrgCertificateImg(reqBean.getInfo("orgCertificateImg"));
        customer.setTaxCertificate(reqBean.getInfo("taxCertificate"));
        customer.setTaxCertificateImg(reqBean.getInfo("taxCertificateImg"));
        customer.setContacts(reqBean.getInfo("contacts"));
        customer.setContactsPhone(reqBean.getInfo("contactsPhone"));
        customer.setProvince(reqBean.getInfo("province"));
        customer.setCity(reqBean.getInfo("city"));
        customer.setCounty(reqBean.getInfo("county"));
        customer.setStatus(reqBean.getInfo("status"));
        customer.setAddress(reqBean.getInfo("address"));
        customer.setRemark(reqBean.getInfo("remark"));

        return customer;
    }

    /**
     * 查询客户合同
     * 
     * @param reqBean
     * @return
     */
    public JSONObject queryContract(ReqBean reqBean) {

        String customerId = reqBean.getInfo("customerId");
        if (StringUtils.isBlank(customerId)) {
            throw new BusinessException("缺少参数!");
        }

        String sql = "SELECT * FROM `AD_CONTRACT` a where a.CUSTOMER_ID = '" + customerId + "'";
        return queryTable(new SqlBuilder(sql).addWhereLike2("a.CONTRACT_NO", reqBean.getInfo("contractNo")),
                reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 查询用户下拉树
     * @param reqBean
     * @return
     */
    public JSONArray queryCustomer(ReqBean reqBean) {
        String sql = "SELECT a.CUSTOMER_ID,a.CUSTOMER_NAME,a.STATUS FROM AD_CUSTOMER a";

        return query(new SqlBuilder(sql).addWhere("a.CUSTOMER_ID", reqBean.getInfo("customerId")));
    }

    /**
     * 查询客户全部合同
     * 
     * @param reqBean
     * @return
     */
    public JSONObject getContracts4Customer(ReqBean reqBean) {
		JSONObject result = new JSONObject();
        String customerId = reqBean.getInfo("customerId");
        if (StringUtils.isBlank(customerId)) {
            throw new BusinessException("缺少参数!");
        }
        String sql = "SELECT a.CONTRACT_ID,a.CONTRACT_TITLE FROM `AD_CONTRACT` a where a.CUSTOMER_ID = '" + customerId + "'";
        result.put("contracts", this.query(sql));
        return result;
    }
    
    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    public JSONObject findCustomerResSchedule(ReqBean reqBean) {
        JSONObject json = new JSONObject();
        
        String currentMonth = reqBean.getInfo("month");// 当前月份
        String lastOrNext = reqBean.getInfo("lastOrNext");// -1：上一月/年 1：下一月/年
        String monthOrYear = reqBean.getInfo("monthOrYear");// 1:年 2：月
        String customerId = reqBean.getInfo("customerId");//客户id
        String resourceParentType = reqBean.getInfo("resourceParentType");// 资源父类型
        String resourceType = reqBean.getInfo("resourceType");// 资源子类型
        String contractId = reqBean.getInfo("contractId");// 合同id
        
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(StringUtil.isEmpty(currentMonth) ? new Date() : (DateUtil.parse(currentMonth + "-01")));
        
        if(StringUtil.isNotEmpty(lastOrNext) && StringUtil.isNotEmpty(monthOrYear)){
        	calendar.add(Integer.valueOf(monthOrYear), Integer.valueOf(lastOrNext));
        }
        String queryDateStr = DateUtil.formatDate(calendar.getTime());
        
        int year = calendar.get(Calendar.YEAR);
        ArrayList<String> monthsList = new ArrayList<String>();
        for (int i = 1; i <= 12; i++) {
            monthsList.add(year + "-" + i);
        }
        currentMonth = monthsList.get(calendar.get(Calendar.MONTH));
        JSONArray daysArray =  DateUtil.getDaysArray(queryDateStr);
        
       
        
        SqlBuilder sql = new SqlBuilder("SELECT ac.CONTRACT_ID, ac.CONTRACT_NO, ac.CONTRACT_TITLE, ac.CUSTOMER_ID, acr.RESOURCE_ID, mr.RESOURCE_NAME,mr.MODEL ");
        sql.appendSql("FROM AD_CONTRACT ac");
        sql.appendSql(" inner JOIN AD_CONTRACT_RESOURCE acr ON ac.CONTRACT_ID = acr.CONTRACT_ID");
        sql.appendSql(" inner JOIN MEDIA_RESOURCE mr ON mr.RESOURCE_ID = acr.RESOURCE_ID");
      
        
        if(Constant.MEDIA_TYPE_STOP.equals(resourceParentType)){// 站点
        	   sql.appendSql(" INNER JOIN MEDIA_TYPE t on  mr.MEDIA_TYPE = t.MEDIA_ID ");
               sql.appendSql(" LEFT JOIN MEDIA_STOP s ON mr.STOP_ID = s.STOP_ID");
        }else if(Constant.MEDIA_TYPE_BUS.equals(resourceParentType)){
        	   sql.appendSql(" INNER JOIN MEDIA_TYPE t on  mr.MEDIA_TYPE = t.MEDIA_ID ");
               sql.appendSql(" LEFT JOIN MEDIA_BUS b ON mr.BUS_ID = b.BUS_ID");
        }
        sql.appendSql(" where 1=1");
        sql.addWhere("t.PARENT_ID", resourceParentType);
        sql.addWhere("mr.MEDIA_TYPE", resourceType);
        sql.addWhere("ac.CUSTOMER_ID", customerId);
        sql.addWhere("ac.CONTRACT_ID", contractId);
        JSONObject dataJson = this.queryTable(sql, reqBean.getInfoInt("pageSize"),reqBean.getInfoInt("pageIndex"));
        
        int totalPages = dataJson.getInt("total") % reqBean.getInfoInt("pageSize") == 0 ? dataJson.getInt("total")
                / reqBean.getInfoInt("pageSize") : dataJson.getInt("total") / reqBean.getInfoInt("pageSize") + 1;
        JSONArray rows = dataJson.getJSONArray("rows");
        
        for (int i = 0; i < rows.size(); i++) {
            JSONObject o = rows.getJSONObject(i);
	        String resourceId = o.getString("resourceId");
            o.put("scheduleArray", getScheduleArray(resourceId, daysArray));
        }

        json.put("months", monthsList);// 全部月份
        json.put("currentMonth", monthsList.get(calendar.get(Calendar.MONTH)));// 当前查询月份
        json.put("lastYear", calendar.get(Calendar.YEAR) - 1);// 上一年
        json.put("nextYear", calendar.get(Calendar.YEAR) + 1);// 下一年
        json.put("daysArray", daysArray);// 当月日期、星期
        json.put("dataArray", rows);// 最终数据
        json.put("totalPages", totalPages);// 总页数
        return json;
    }
    
    // 客户资源状态：空闲、锁定（上刊申请中）、上刊
    public JSONArray getScheduleArray(String resourceId, JSONArray daysArray) {
        // 获得月初和月末
        String beginOfMonth = daysArray.getJSONObject(0).getString("date");
        String endOfMonth = daysArray.getJSONObject(daysArray.size() - 1).getString("date");
        HashMap<String, JSONObject> dateResourceIdMap = new HashMap<String, JSONObject>();
        
        getResouceInfoForWorkOff(dateResourceIdMap, resourceId, beginOfMonth, endOfMonth);// 处理客户已有资源信息
        getResouceInfoForLocked(dateResourceIdMap, resourceId, beginOfMonth, endOfMonth);// 处理未审核通过的上刊资源信息
        getResouceInfoForPublished(dateResourceIdMap, resourceId, beginOfMonth, endOfMonth );// 处理已审核通过的上刊资源信息

        JSONArray scheduleArray = new JSONArray();
        for (int i = 0; i < daysArray.size(); i++) {
            JSONObject o = daysArray.getJSONObject(i);
            JSONObject info = dateResourceIdMap.get(o.getString("date"));
            if (info == null) {
                JSONObject nullInfo = new JSONObject();
                nullInfo.put("status", Constant.SCHEDULE_CSS_FREE);//不可用
                scheduleArray.add(nullInfo);
            } else {
                scheduleArray.add(info);
            }
        }
        return scheduleArray;
    }
    
    /**
     * 处理已上刊资源信息，查出合同、上刊单
     * 
     * @param dateResourceIdMap
     * @param resourceId
     * @param beginOfMonth
     * @param endOfMonth
     */
	public void getResouceInfoForPublished(HashMap<String, JSONObject> dateResourceIdMap, String resourceId,
            String beginOfMonth, String endOfMonth) {
        // 先查询合同表确定是否售出状态，再查询上刊表确定是否已上刊状态
		
		StringBuffer sql = new StringBuffer("select r.* ");
        sql.append(" ,c.BILL_NO, c.BILL_TYPE, c.APPLY_TIME ");
        sql.append(" FROM AD_PUBLISH_BILL_DETAIL r ");
        sql.append(" INNER JOIN AD_PUBLISH_BILL c ON r.BILL_ID = c.BILL_ID ");
        sql.append(" where r.RESOURCE_ID = '").append(resourceId).append("'");
        sql.append(" and r.PUBLISH_TIME <= '").append(endOfMonth).append("'");
        sql.append(" and r.PUBLISH_OFF_TIME >= '").append(beginOfMonth).append("'");
        sql.append(" and c.`STATUS`='").append(Constant.PUBLISH_BILL_STATUS_AUDIT_TRUE).append("'");//审核通过
        sql.append(" order by r.PUBLISH_TIME ");
       
        JSONArray publishedArray = this.query(sql.toString());

        Date beginOfMonthDate = DateUtil.parse(beginOfMonth);// 月初
        Date endOfMonthDate = DateUtil.parse(endOfMonth);// 月末
        for (int i = 0; i < publishedArray.size(); i++) {
            JSONObject o = publishedArray.getJSONObject(i);
            String startDateStr = o.getString("publishTime");// 上刊时间
            String endDateStr = o.getString("publishOffTime");// 下刊时间
            
            Date startDate = DateUtil.parse(startDateStr);
            Date endDate = DateUtil.parse(endDateStr);

            // 如果开始时间小于月初，则将开始时间调至月初；如果接受时间大于月末，则将结束时间调至月末

            if (startDate.before(beginOfMonthDate)) {// 如果开始时间小于月初，则将开始时间调至月初；
                startDate = beginOfMonthDate;
            }
            if (endDate.after(endOfMonthDate)) {// / 如果结束时间小于月末，则将结束时间调至月末；
                endDate = endOfMonthDate;
            }

            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startDate);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endDate);

            while (endCalendar.after(startCalendar) || endCalendar.equals(startCalendar)) {
                String dateStr = DateUtil.formatDate(startCalendar.getTime());// 日期
                JSONObject resouceInfo = dateResourceIdMap.get(dateStr);
                resouceInfo = resouceInfo == null ? new JSONObject() : resouceInfo;
                //resouceInfo.put("bill", o);
                resouceInfo.put("status", Constant.SCHEDULE_CSS_PUBLISHED);
                dateResourceIdMap.put(dateStr, resouceInfo);
                startCalendar.add(Calendar.DATE, 1);
            }
        }
    }
	
	 /**
     * // 处理客户已有资源信息
     * 
     * @param dateResourceIdMap
     * @param resourceId
     * @param beginOfMonth
     * @param endOfMonth
     */
    public void getResouceInfoForWorkOff(HashMap<String, JSONObject> dateResourceIdMap, String resourceId,
            String beginOfMonth, String endOfMonth) {
        Date beginOfMonthDate = DateUtil.parse(beginOfMonth);// 月初
        Date endOfMonthDate = DateUtil.parse(endOfMonth);// 月末
        // 先查询合同表确定是否售出状态，再查询上刊表确定是否已上刊状态
        StringBuffer sql = new StringBuffer("select r.* ");
        sql.append(" FROM AD_CONTRACT_RESOURCE r ");
        sql.append(" where r.RESOURCE_ID = '").append(resourceId).append("'");
        sql.append(" and r.START_DATE <= '").append(endOfMonth).append("'");
        sql.append(" and r.END_DATE >= '").append(beginOfMonth).append("'");
        
        JSONArray contractResources = this.query(sql.toString());

        for (int i = 0; i < contractResources.size(); i++) {
            JSONObject o = contractResources.getJSONObject(i);
            String startDateStr = o.getString("startDate");
            String endDateStr = o.getString("endDate");

            Date startDate = DateUtil.parse(startDateStr);
            Date endDate = DateUtil.parse(endDateStr);

            // 如果开始时间小于月初，则将开始时间调至月初；如果接受时间大于月末，则将结束时间调至月末

            if (startDate.before(beginOfMonthDate)) {// 如果开始时间小于月初，则将开始时间调至月初；
                startDate = beginOfMonthDate;
            }
            if (endDate.after(endOfMonthDate)) {// 如果结束时间小于月末，则将结束时间调至月末；
                endDate = endOfMonthDate;
            }

            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startDate);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endDate);

            while (endCalendar.after(startCalendar) || endCalendar.equals(startCalendar)) {
                String dateStr = DateUtil.formatDate(startCalendar.getTime());// 日期
                JSONObject resouceInfo = dateResourceIdMap.get(dateStr);
                resouceInfo = resouceInfo == null ? new JSONObject() : resouceInfo;
               // resouceInfo.put("contract", o);
                resouceInfo.put("status", Constant.SCHEDULE_CSS_WORKOFF);
                dateResourceIdMap.put(dateStr, resouceInfo);
                startCalendar.add(Calendar.DATE, 1);
            }
        }
    }
    
    /**
     * 处理未审核通过的上刊资源信息
     * 
     * @param dateResourceIdMap
     * @param resourceId
     * @param beginOfMonth
     * @param endOfMonth
     */
    public void getResouceInfoForLocked(HashMap<String, JSONObject> dateResourceIdMap, String resourceId,
            String beginOfMonth, String endOfMonth) {
        Date beginOfMonthDate = DateUtil.parse(beginOfMonth);// 月初
        Date endOfMonthDate = DateUtil.parse(endOfMonth);// 月末
    	
		StringBuffer sql = new StringBuffer("select r.* ");
        sql.append(" ,c.BILL_NO, c.BILL_TYPE, c.APPLY_TIME ");
        sql.append(" FROM AD_PUBLISH_BILL_DETAIL r ");
        sql.append(" INNER JOIN AD_PUBLISH_BILL c ON r.BILL_ID = c.BILL_ID ");
        sql.append(" where r.RESOURCE_ID = '").append(resourceId).append("'");
        sql.append(" and r.PUBLISH_TIME <= '").append(endOfMonth).append("'");
        sql.append(" and r.PUBLISH_OFF_TIME >= '").append(beginOfMonth).append("'");
        sql.append(" and c.`STATUS`!='").append(Constant.PUBLISH_BILL_STATUS_AUDIT_TRUE).append("'");//未审核通过
        sql.append(" order by r.PUBLISH_TIME ");
        
        JSONArray bidReourceArray = this.query(sql.toString());

        for (int i = 0; i < bidReourceArray.size(); i++) {
            JSONObject o = bidReourceArray.getJSONObject(i);
            String startDateStr = o.getString("publishTime");
            String endDateStr = o.getString("publishOffTime");

            Date startDate = DateUtil.parse(startDateStr);
            Date endDate = DateUtil.parse(endDateStr);

            // 如果开始时间小于月初，则将开始时间调至月初；如果接受时间大于月末，则将结束时间调至月末

            if (startDate.before(beginOfMonthDate)) {// 如果开始时间小于月初，则将开始时间调至月初；
                startDate = beginOfMonthDate;
            }
            if (endDate.after(endOfMonthDate)) {// 如果结束时间小于月末，则将结束时间调至月末；
                endDate = endOfMonthDate;
            }

            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startDate);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endDate);

            while (endCalendar.after(startCalendar) || endCalendar.equals(startCalendar)) {
            	String dateStr = DateUtil.formatDate(startCalendar.getTime());// 日期
                JSONObject resouceInfo = dateResourceIdMap.get(dateStr);
                resouceInfo = resouceInfo == null ? new JSONObject() : resouceInfo;
                //resouceInfo.put("bid", o);
                resouceInfo.put("status", Constant.SCHEDULE_CSS_LOCKED);
                dateResourceIdMap.put(dateStr, resouceInfo);
                startCalendar.add(Calendar.DATE, 1);
            }
        }
    }
}
